<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.postName" class="list-input" placeholder="搜索岗位名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.postName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>

    </view>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:post:add'])">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="post in postList" :key="post.postId" class="list-item" @click="handleView(post)">
        <view class="list-avatar">
          <uni-icons type="person-filled" size="24" color="#007aff"/>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ post.postName }}</text>
            <text class="list-subtitle">岗位编码: {{ post.postCode }}</text>
            <view class="status-badge" :class="post.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ post.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">编号：{{ post.postId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="up-down" size="14" color="#999"/>
              <text class="detail-text">第{{ post.postSort }}位</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(post.createTime, '{y}-{m}-{d}') }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleUpdate(post)"
                v-if="checkPermission(['system:post:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(post)"
                v-if="checkPermission(['system:post:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="postList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && postList.length === 0" class="list-empty">
      <uni-icons type="person" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无岗位数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:post:add'])">添加岗位</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {delPost, listPost} from '@/api/system/post'
import {parseTime} from '@/utils/ruoyi'


import {usePermission} from '@/utils/permission'

const {proxy} = getCurrentInstance()


const checkPermission = usePermission()

// 数据定义
const postList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  postName: '',
  postCode: '',
  status: ''
})

let searchTimer = null

// 页面加载
onMounted(() => {
  getList()
})

// 获取岗位列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listPost(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        postList.value = newData
      } else {
        postList.value.push(...newData)
      }

      total.value = response.total || 0

      if (postList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    proxy.$modal.showToast('获取岗位列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 事件处理
function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.postName = '';
  handleQuery()
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  postList.value = []
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: './edit?mode=add'
  })
}

function handleUpdate(post) {
  uni.navigateTo({
    url: `./edit?mode=edit&postId=${post.postId}`
  })
}

function handleView(post) {
  uni.navigateTo({
    url: `./edit?mode=view&postId=${post.postId}`
  })
}

async function handleDelete(post) {
  try {
    await proxy.$modal.confirm(`确认要删除岗位"${post.postName}"吗？`)

    const response = await delPost(post.postId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除岗位失败:', error)
  }
}

function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>